<template>
  <div class="create-order">
    <nav-bar>
      <template v-slot:default>订单预览</template>
    </nav-bar>
    <div class="address-wrap" @click="goTo">
      <div class="name">
        <span>{{ address.name }}</span>
        <span>{{ address.phone }}</span>
      </div>
      <div class="address">
        {{ address.province }}{{ address.city }}{{ address.county }} {{ address.address }}
      </div>
      <van-icon name="arrow" class="arrow"></van-icon>
    </div>
    <div class="good">
      <div class="good-item" v-for="item in cartList" :key="item.id">
        <div class="good-img">
          <img v-lazy="item.goods.cover_url" alt="">
        </div>
        <div class="good-desc">
          <div class="good-title">
            <span>{{ item.goods.title }}</span>
            <span>x{{ item.num }}</span>
          </div>
          <div class="good-btn">
            <div class="price"><small>￥</small>{{ item.goods.price }}</div>
          </div>
        </div>
      </div>
    </div>
    <van-submit-bar class="submit-all" :price="total*100" button-text="生成订单" @submit="handleCreateOrder">
      商品金额
    </van-submit-bar>
    <van-popup closeable
               :close-on-click-overlay="false"
               v-model:show="isShow"
               position="bottom"
               style="height:30%"
               @close="close">

      <van-grid :border="true" :column-num="2">
        <van-grid-item>
          支付宝二维码
          <van-image width="150px" height="150px" :src="aliyunQR_url"/>
        </van-grid-item>
        <van-grid-item>
          微信二维码
          <van-image width="150px" height="150px" :src="wechatQR_url"/>
        </van-grid-item>
      </van-grid>

    </van-popup>
  </div>
</template>

<script>
import {computed, defineComponent, onMounted, reactive, toRefs} from 'vue'
import NavBar from "../../../components/common/navbar/NavBar";
import {useRoute, useRouter} from "vue-router";
import {Toast} from "vant";
import {createOrder, getOrderPreview, payOrder, payOrderStatus} from "../../../network/order";
import {useStore} from "vuex";

export default defineComponent({
  name: "CreateOrder",
  components: {
    NavBar
  },
  setup() {
    const router = useRouter();
    const store = useStore();
    const entryData = reactive({
      cartList: [],// 购物车列表
      address: {},// 默认地址
      isShow: false,// 是否显示支付方式选择pop
      orderId: '',// 订单ID,
      aliyunQR_url: '',// 阿里云支付二维码
      wechatQR_url: '',// 微信支付二维码
    });
    // 初始化数据
    const initData = () => {
      Toast.loading({message: '加载中...', forbidClick: true});
      getOrderPreview().then(res => {
        // 过滤找出默认地址
        let address = res.address.filter(n => n.is_default === 1);
        if (address.length === 0) {
          entryData.address = {
            address: `还没有设置默认地址，请选择或填写地址信息`
          }
        } else {
          entryData.address = address[0];
        }
        entryData.cartList = res.carts;
        Toast.clear();
      });
    }
    onMounted(() => {
      initData();
    });

    // 通过计算属性计算总价
    const total = computed(() => {
      let sum = 0;
      entryData.cartList.forEach(item => {
        sum += item.num * item.goods.price;
      });
      return sum;
    })
    // 跳转到地址选择列表
    const goTo = () => {
      router.push({path: '/addresslist'});
    }
    // 生成订单
    const handleCreateOrder = () => {
      const params = {
        address_id: entryData.address.id
      }
      createOrder(params).then(res => {
        console.log(res);
        // Toast('创建成功！');
        store.dispatch('updateCart');// 改变vuex中购物车的状态数量
        entryData.isShow = true;
        entryData.orderId = res.id;// 将订单ID给数据实体
        payOrder(entryData.orderId, {type: 'aliyun'}).then(res => {
          entryData.aliyunQR_url = res.qr_code_url;
          entryData.wechatQR_url = res.qr_code_url;
        })

        // 轮询查看
        const timer = setInterval(() => {
          payOrderStatus(entryData.orderId).then(res => {
            if (res === 2) {
              clearInterval(timer);
              router.push({path: '/orderdetail', query: {orderId: entryData.orderId}});
            }

          });
        }, 2000);
      });
    }

    // 关闭支付方式选择pop时触发
    const close = () => {
      router.push({path: '/orderdetail', query: {orderId: entryData.orderId}});
    }
    return {
      ...toRefs(entryData),
      total,
      goTo,
      handleCreateOrder,
      close
    }
  }
})
</script>

<style lang="scss" scoped>
.create-order {
  background: #f9f9f9;

  .address-wrap {
    text-align: left;
    margin-bottom: 20px;
    background: #fff;
    position: relative;
    margin-top: 44px;
    font-size: 14px;
    padding: 15px;
    color: #222333;

    .name, .address {
      margin: 10px 0;
    }

    .arrow {
      position: absolute;
      right: 10px;
      top: 50%;
      transform: translateY(-50%);
      font-size: 20px;
    }

    &::before {
      position: absolute;
      right: 0;
      bottom: 0;
      left: 0;
      height: 2px;
      background: -webkit-repeating-linear-gradient(135deg, #ff6c6c 0, #ff6c6c 20%, transparent 0, transparent 25%, #1989fa 0, #1989fa 45%, transparent 0, transparent 50%);
      background: repeating-linear-gradient(-45deg, #ff6c6c 0, #ff6c6c 20%, transparent 0, transparent 25%, #1989fa 0, #1989fa 45%, transparent 0, transparent 50%);
      background-size: 80px;
      content: '';
    }
  }

  .good {
    margin-bottom: 120px;
  }

  .good-item {
    padding: 10px;
    background: #fff;
    display: flex;
    border-bottom: 1px solid #42bBaa;

    .good-img {
      img {
        width: 100px;
        height: auto;
      }
    }

    .good-desc {
      display: flex;
      flex-direction: column;
      justify-content: space-between;
      flex: 1;
      padding: 20px;

      .good-title {
        display: flex;
        justify-content: space-between;
      }

      .good-btn {
        display: flex;
        justify-content: space-between;

        .price {
          font-size: 16px;
          color: red;
          line-height: 28px;
        }

        .van-icon-delete {
          font-size: 20px;
          margin-top: 4px;
        }
      }
    }
  }

  .pay-wrap {
    position: fixed;
    bottom: 0;
    left: 0;
    width: 100%;
    background: #fff;
    padding: 10px 0;
    padding-bottom: 50px;
    border-top: 1px solid #e9e9e9;

    > div {
      display: flex;
      justify-content: space-between;
      padding: 0 5%;
      margin: 10px 0;
      font-size: 14px;

      span:nth-child(2) {
        color: red;
        font-size: 18px;
      }
    }

    .pay-btn {
      position: fixed;
      bottom: 7px;
      right: 0;
      left: 0;
      width: 90%;
      margin: 0 auto;
    }
  }
}

.submit-all {
  margin-bottom: 50px;
  z-index: 9 !important;
}
</style>
